#include "usart.h"

#pragma import(__use_no_semihosting)


struct __FILE
{
	int handle;
};
FILE __stdout;

void _sys_exit(int x)
{
	x = x;
}

int fputc(int ch, FILE *f)
{
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE) == RESET);
	USART_SendData(USART1, ch);
	return ch;
}

void usart_init(void)
{
	USART_InitTypeDef USART_InitType;
	GPIO_InitTypeDef GPIO_InitStruct;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
	
	USART_InitType.USART_BaudRate = 115200;
	USART_InitType.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitType.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	USART_InitType.USART_Parity = USART_Parity_No;
	USART_InitType.USART_StopBits = USART_StopBits_1;
	USART_InitType.USART_WordLength = USART_WordLength_8b;
	
	USART_Init(USART1,&USART_InitType);
	
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
	GPIO_InitStruct.GPIO_Speed = GPIO_High_Speed;
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(GPIOA,&GPIO_InitStruct);
	
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);
	
	USART_Cmd(USART1,ENABLE);
}

